package com.bibrApp.difu.api;

import android.util.Log;


import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;

import androidx.annotation.NonNull;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;

/**
 * Created by jaylm
 * on 2018/11/19.
 */
public class LogInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private static final String TAG = "okhttp_request";

    @Override
    public okhttp3.Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        Log.i(TAG, "----> START_REQUEST ");
        Log.i(TAG, String.format(Locale.getDefault(), "requestUrl:%s", request.toString()));
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (charset != null) {
                Log.i(TAG, String.format(Locale.getDefault(), "request:%s", buffer.readString(charset)));
            }
        }

        long t1 = System.nanoTime();
        okhttp3.Response response = chain.proceed(chain.request());
        long t2 = System.nanoTime();
        Log.i(TAG, String.format(Locale.getDefault(), "Received response for %s in %.1fms%n",
                response.request().url(), (t2 - t1) / 1e6d));
        assert response.body() != null;
        MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        Log.i(TAG, String.format(Locale.getDefault(), "response body:%s", content));
        Log.i(TAG, "----> END_RESPONSE\n ");
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }

}